package com.jlf.starter.mp;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.MyTableInfo;
import com.baomidou.mybatisplus.core.metadata.MyTableInfoHelper;
import com.jlf.core.domain.Creator;
import com.jlf.core.domain.Updater;
import com.jlf.core.ngac.context.NgacContext;
import com.jlf.core.ngac.domain.Session;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * 自动填充的处理器
 *
 * @author wujr
 * 2023/7/5
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/7/5 1.0 新增]
 */
public class AutofillMetaObjectHandler implements MetaObjectHandler {

    @Override
    public MyTableInfo findTableInfo(MetaObject metaObject) {
        return MyTableInfoHelper.getTableInfo(metaObject.getOriginalObject().getClass());
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        Session session = NgacContext.session();
        MyTableInfo tableInfo = findTableInfo(metaObject);
        Class<?> entityClass = tableInfo.getEntityType();
        if (Creator.class.isAssignableFrom(entityClass)){
            // 创建时间，取当前时间
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            // 创建人主体id
            this.strictInsertFill(metaObject, "createProfileId", Long.class, session.profileId());
            // 创建人身份id
            this.strictInsertFill(metaObject, "createIdentityId", Long.class, session.identityId());
            // 当前操作的执行归属应用编码
            this.strictInsertFill(metaObject, "createAppCode", String.class, session.applicationCode());
            // 当前创建人的姓名
            this.strictInsertFill(metaObject, "createUsername", String.class, session.nickname());
        }

        updateUpdater(session, entityClass, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Session session = NgacContext.session();
        MyTableInfo tableInfo = findTableInfo(metaObject);
        Class<?> entityClass = tableInfo.getEntityType();
        updateUpdater(session, entityClass, metaObject);
    }
    private void updateUpdater(Session session, Class<?> domainClass, MetaObject metaObject){
        if (Updater.class.isAssignableFrom(domainClass)){
            // 更新时间，取当前时间
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            // 更新人主体id
            this.strictInsertFill(metaObject, "updateProfileId", Long.class, session.profileId());
            // 更新人身份id
            this.strictInsertFill(metaObject, "updateIdentityId", Long.class, session.identityId());
            // 当前操作的执行归属应用编码
            this.strictInsertFill(metaObject, "updateAppCode", String.class, session.applicationCode());
            // 当前创建人的姓名
            this.strictInsertFill(metaObject, "updateUsername", String.class, session.nickname());
        }
    }
}
